<template>
    <div class="workflow-edit">
        <el-steps :active="currentStep" finish-status="success" class="steps">
            <el-step title="基本信息" />
            <el-step title="参数配置" />
        </el-steps>

        <div class="form-container">
            <div v-show="currentStep === 0">
                <WorkflowForm
                    :workflow="workflowData"
                    @next="handleNext"
                    @cancel="handleCancel"
                />
            </div>
            <div v-show="currentStep === 1">
                <WorkflowParams
                    :workflow="workflowData"
                    @prev="handlePrev"
                    @save="handleSave"
                />
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import WorkflowForm from '@/components/workflow/WorkflowForm.vue';
import WorkflowParams from '@/components/workflow/WorkflowParams.vue';
import { workflowApi } from '@/api/workflow';
import type { WorkflowTemplate, ParamNode } from '@/types';
import { ParamManager } from '@/components/workflow/params/ParamManager';

const props = defineProps<{
    id?: string;
    isCreate?: boolean;
}>();

const router = useRouter();
const route = useRoute();
const currentStep = ref(0);
const workflowData = ref<Partial<WorkflowTemplate>>({});
const paramManager = new ParamManager();

// 加载工作流数据
const loadWorkflow = async () => {
    try {
        const id = route.params.id as string || props.id;
        if (!id) {
            throw new Error('无效的工作流 ID');
        }
        if (id === 'create') {
            initializeNewWorkflow();
            return;
        }
        
        console.log('Loading workflow:', id);
        const response = await workflowApi.getWorkflow(id);
        if (!response?.data?.data) {
            throw new Error('工作流不存在');
        }
        
        workflowData.value = response.data.data;
        // 初始化参数管理器
        if (workflowData.value.comfyuiJson) {
            paramManager.setWorkflowJson(workflowData.value.comfyuiJson);
        }
    } catch (error) {
        console.error('Load workflow error:', error);
        ElMessage.error(error.message || '加载工作流失败');
        router.push('/workflow');
    }
};

// 初始化新工作流
const initializeNewWorkflow = () => {
    console.log('Initializing new workflow with default values');
    workflowData.value = {
        name: '',
        description: '',
        category: '',
        tags: [],
        thumbnail: '',
        comfyuiJson: null,
        isPublic: false,
        version: '1.0.0',
        rows: 10,
        params: [],
        detailImage: '',
        servers: [],
        excludeServers: [],
        powerConsumption: 0,
        sort: 0,
        showcases: [],
        stats: {
            uses: 0,
            likes: 0,
            views: 0
        }
    };
    console.log('New workflow initialized');
};

// 处理下一步
const handleNext = (data: Partial<WorkflowTemplate>) => {
    workflowData.value = {
        ...workflowData.value,
        ...data
    };
    // 更新参数管理器
    if (data.comfyuiJson) {
        paramManager.setWorkflowJson(data.comfyuiJson);
    }
    currentStep.value = 1;
};

// 处理上一步
const handlePrev = () => {
    currentStep.value = 0;
};

// 处理取消
const handleCancel = () => {
    router.push('/workflow');
};

// 处理保存
const handleSave = async (params: ParamNode[]) => {
    try {
        if (!workflowData.value.name || !workflowData.value.description || !workflowData.value.category) {
            throw new Error('基本信息不完整');
        }

        // 应用参数到工作流
        const finalData = paramManager.applyParamsToWorkflow(workflowData.value);

        let savedWorkflowId: string;
        
        if (workflowData.value.id) {
            await workflowApi.updateWorkflow(
                workflowData.value.id, 
                finalData
            );
            ElMessage.success('更新成功');
            savedWorkflowId = workflowData.value.id;
        } else {
            const { data } = await workflowApi.createWorkflow(
                finalData as WorkflowTemplate
            );
            ElMessage.success('创建成功');
            savedWorkflowId = data.id;
        }
        
        router.push({
            name: 'WorkflowPreview',
            params: { id: savedWorkflowId },
            query: { from: 'edit' }
        });
    } catch (error) {
        console.error('Save workflow error:', error);
        ElMessage.error(error.response?.data?.message || error.message || '保存失败');
    }
};

// 初始化时加载数据
onMounted(() => {
    const id = route.params.id as string;
    console.log('Route ID:', id);
    
    loadWorkflow();
});
</script>

<style lang="scss" scoped>
.workflow-edit {
    padding: 20px;

    .steps {
        max-width: 800px;
        margin: 0 auto 40px;
    }

    .form-container {
        background: #fff;
        border-radius: 4px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        min-height: 400px;
        padding: 20px;
        
        > div {
            height: 100%;
        }
    }
}
</style> 